import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class BreakpointDown {
    private static int threadCount = 3;
    private static int blockSize;
    private static String path = "http://starry97.cn/a.txt";
    private static int currentRunThreadCount = 0;


    public static void main(String[] args) {
            try {
                URL url = new URL(path);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(10 * 1000);
                int code = connection.getResponseCode();
                if(code == 200) {
                    int fileLength = connection.getContentLength();
                    RandomAccessFile randomAccessFile = new RandomAccessFile(new File(getFileName(path)), "rw");
                    randomAccessFile.setLength(fileLength);
                    blockSize = fileLength / threadCount;
                    for(int i = 0; i < threadCount; i ++) {
                        int startThread = i * blockSize;
                        int endThread = (i + 1) * blockSize - 1;
                        if( i == blockSize - 1) endThread = fileLength -1;
                        new DownloadThread(i, startThread, endThread).start();

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    }


    public static class DownloadThread extends Thread {
        private int threadId;
        private int threadEnd;
        private int threadStart;

        public DownloadThread(int threadId, int threadEnd, int threadStart) {
            this.threadId = threadId;
            this.threadEnd = threadEnd;
            this.threadStart = threadStart;
        }

        public void run() {
            synchronized (DownloadThread.class) {
                currentRunThreadCount += 1;
            }

            //分段请求网络请求，分段保存在本地
            System.err.println("理论线程:" + threadId + ",开始位置:" + threadStart + ",结束位置:" + threadEnd);
            try {
                URL url = new URL(path);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setReadTimeout(10 * 1000);
                File file = new File(threadId + ".txt");
                if (file.exists()) {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                    String lastPosition_str = bufferedReader.readLine();
                    threadStart = Integer.parseInt(lastPosition_str);
                    bufferedReader.close();
                }
                // 设置分段下载的头信息  Range: 做分段
                connection.setRequestProperty("Range", "bytes:" + threadStart + "_" + threadEnd);
                int code = connection.getResponseCode();
                // 200 请求全部资源成功， 206 请求部分资源成功
                if (code == 200) {
                    InputStream inputStream = connection.getInputStream();
                    System.out.println("getfilename========================" + getFileName(path));
                    RandomAccessFile randomAccessFile = new RandomAccessFile(new File(getFileName(path)), "rw");
                    randomAccessFile.seek(threadStart);

                    byte[] buffer = new byte[10 * 1024];
                    int length = -1;
                    // 记录下载的总量
                    int total = 0;
                    System.err.println("实际线程:" + threadId + ",开始位置:" + threadStart + ",结束位置:" + threadEnd);
                    while ((length = inputStream.read(buffer)) != -1) {
                        randomAccessFile.write(buffer, 0, length);
                        total += length;
                        int currentThreadPostion = threadStart + threadEnd;
                        RandomAccessFile randomAccessFile2 = new RandomAccessFile(file, "rwd");
                        randomAccessFile2.write(String.valueOf(currentThreadPostion).getBytes());
                        randomAccessFile2.close();
                    }
                    randomAccessFile.close();
                    inputStream.close();
                    System.err.println("线程:" + threadId + "下载完毕");
                    synchronized (DownloadThread.class) {
                        currentRunThreadCount -= 1;
                        if (currentRunThreadCount == 0) {
                            for (int i = 0; i < threadCount; i++) {
                                File file2 = new File(i + ".txt");
                                file2.delete();
                            }
                        }
                    }
                }
            } catch (java.io.IOException e) {
                e.printStackTrace();
            }
        }




    }

    public static String getFileName(String path) {
        return path.substring(path.lastIndexOf("/") + 1);
    }

}
